package elements.labels ;
import charts.Base;
import charts.ObjectCollection;
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFormat;
//import org.flashdevelop.utils.FlashConnect;

class Keys extends Sprite {
	var _height: Float;
	var count: Float;
	public var colors:Array<Int>; // NOTE: Fucking colors are Int
	
	public function new( stuff:ObjectCollection )
	{
		super();
		_height = 0;
		count = 0;


		this.colors = new Array<Int>();
		
		var key: Float = 0;
		for ( b in stuff.sets )
		{
			for ( o in b.get_keys() ) {
				
				this.make_key( o.text, Reflect.field(o,'font-size'), cast(o.color,Int) );
				this.colors.push( cast(o.color,Int) );
				key++;

			}
		}
		
		this.count = key;
	}
	
	// each key is a MovieClip with text on it
		function make_key( text:String, font_size: Float, color: Int ) : Void
	{

		var tf:TextField = new TextField();
		
		tf.text = text;
		var fmt:TextFormat = new TextFormat();
		fmt.color = color;
		fmt.font = "Verdana";
		fmt.size = font_size;
		fmt.align = flash.text.TextFormatAlign.LEFT;
		
		tf.setTextFormat(fmt);
		tf.autoSize = flash.text.TextFieldAutoSize.LEFT;
	
		this.addChild(tf);
	}
	
	//
	// draw the color block for the data set
	//
	function draw_line( x: Float, y: Float, height: Float, color: Int ): Float {
		y += (height / 2);
		this.graphics.beginFill( color, 100 );
		this.graphics.drawRect( x, y - 1, 10, 2 );
		this.graphics.endFill();
		return x+12;
	}

	// shuffle the keys Into place, keeping note of the total
	// height the key block has taken up
	public function resize( x: Float, y: Float ):Void {
		if( this.count == 0 )
			return;
		
		this.x = x;
		this.y = y;
		
		var height: Float = 0;
		var x: Float = 0;
		var y: Float = 0;
		
		this.graphics.clear();
		
		for ( i in 0...this.numChildren )
		{
			var width: Float = this.getChildAt(i).width;
			
			if( ( this.x + x + width + 12 ) > this.stage.stageWidth )
			{
				// it is past the edge of the stage, so move it down a line
				x = 0;
				y += this.getChildAt(i).height;
				height += this.getChildAt(i).height;
			}
				
			this.draw_line( x, y, this.getChildAt(i).height, this.colors[i] );
			x += 12;

			this.getChildAt(i).x = x;
			this.getChildAt(i).y = y;
			
			// move next key to the left + some padding between keys
			x += width + 10;
		}
		
		// Ugly code:
		height += this.getChildAt(0).height;
		this._height = height;
	}
	
	public function get_height() : Float {
		return this._height;
	}
	
	public function die(): Void {
		
		this.colors = null;
	
		this.graphics.clear();
		while ( this.numChildren > 0 )
			this.removeChildAt(0);
	}
	
}
